local CommonOHOH = _G.CommonOHOH;
local M = CommonOHOH.class.new(script, CommonOHOH.files.TaskBase());
local DAY_TIME=24*60*60

--任务内容: 累计登录X天

--获取今天和明天的其实时间戳
function GetTodayAndTomorrow(time)
	local day=math.floor(time/DAY_TIME)*DAY_TIME
	return day,day+DAY_TIME
end

function M.new(...)
	return M(...);
end;

function M.ctor(self,player,finish,tId)--构造函数
	M.super.ctor(self,player,finish,tId);
end;

function M.ClientInit(self)--客户端初始化

    self.DataBase=self.Player:GetComponent(_G.ClientOHOH.load.Client_PlayerDataComponent());
    local taskData=self.DataBase:GetData("task")[self.TaskId]

    if not taskData then
        taskData={
            now=1,
            loginTime=os.time()
        }
    end
    self.TaskData=taskData

    self:UpdateProgress()

end

function M.ServerInit(self)--服务器初始化

    self.DataBase=self.Player:GetComponent(_G.ServerOHOH.load.Server_PlayerDataComponent())
    local taskData=self.DataBase:GetData("task")[self.TaskId]

    if not taskData then
        taskData={
            now=1,
            loginTime=os.time()
        }
    end
    self.TaskData=taskData
    self:SaveTaskData()
    self:UpdateProgress()
   
end

function M.UpdateProgress(self)
    self:RemoveConnect()
    local today,tomorrow=GetTodayAndTomorrow(self.TaskData.loginTime)
    local dt=os.time()-tomorrow
    local con= self:AddProcess(function()
        if dt>0 then
            self.TaskData.now=self.TaskData.now+1
            self.TaskData.loginTime=os.time()
            self.UpdateEvent:Action(self)
            self:SaveTaskData()
            if self:IsComplete() then
                self:TaskDone()
            end
        else
            self:Wait(-dt)
            self:UpdateProgress()
        end
    end)
    self:AddConnect(con)
end


function M.SaveTaskData(self)--保存任务数据
    
    self.DataBase:GetData("task")[self.TaskId]= {
        now=self.TaskData.now,
        loginTime=self.TaskData.loginTime,
    }
    if not M.IsClient then
        self.DataBase:Execut(function()
        end);
    end
end


--获取离达成下次登录的时间戳
function M.GetTagLoginTime(self)
    local today,tomorrow=GetTodayAndTomorrow(self.TaskData.loginTime)
    return tomorrow
end

-- 获取任务进度数值
function M.GetProgress(self)
    return self.TaskData.now,self.Finish
end;


--是否完成
function M.IsComplete(self)
    if self.TaskData.now>=self.Finish then
        return true
    end
    return false
end

function M.dtor(self)--析构函数
    M.super.dtor(self);
end;

return M